
package com.wangzha.business.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.wangzha.common.base.service.BaseService;
import com.wangzha.common.kit.SqlKit;
import com.wangzha.common.model.UserRecordGroup;
import com.wangzha.common.vo.Grid;
import org.apache.commons.collections.CollectionUtils;

import java.util.List;

/**
 * 
 * @author qinhailin
 * @date 2021-03-29
 */
public class UserRecordGroupService extends BaseService {
	private UserRecordGroup dao = new UserRecordGroup().dao();

    @Override
   public Model<UserRecordGroup> getDao() {
    	return dao;
   }

   public Grid page(int pageNumber, int pageSize,Record record) {
      Record rd = new Record();
      //rd.set("user_name like", record.getStr("keyword"));
      return queryForList(pageNumber, pageSize,rd);
   }

    public boolean saveUserRecordGroups(List<UserRecordGroup> UserRecordGroupList){
        Db.batchSave(UserRecordGroupList, UserRecordGroupList.size());
        return true;
    }

    public List<UserRecordGroup> findByUserCode(String userCode){
        return getDao().find("select * from " + getTable() + " where user_code = ?", userCode);
    }

    public boolean deleteByUserCodeAndGroupId(String userCode, Long groupId) {
        return Db.delete("delete from " + getTable() + " where id = ? and user_code = ?", groupId, userCode) > 0 ? true : false;
    }


    public List<UserRecordGroup> findByGroupIds(List<Long> groupIds) {
        return getDao().find("select * from " + getTable() + " where id in " + SqlKit.joinId(groupIds));
    }

    public UserRecordGroup findByParentGroupIdAndUserCode(String userCode, Long parentGroupId) {
        return dao.findFirst("select * from " + getTable() + " where user_code = ? and parent_group_id = ?", userCode, parentGroupId);
    }

    public UserRecordGroup findByIdAndUserCode(String userCode, Long groupId) {
        return dao.findFirst("select * from " + getTable() + " where id = ? and user_code = ?", groupId, userCode);
    }

    public List<UserRecordGroup> findByParentGroupIdAndUserCode(String userCode, List<Long> parentGroupIds) {
        return dao.find("select * from " + getTable() + " where user_code = ? and parent_group_id in " + SqlKit.joinId(parentGroupIds), userCode);
    }


    public List<?> findByParentGroupIds(List<String> parentGroupIds) {
        if (CollectionUtils.isEmpty(parentGroupIds)) {
            return null;
        } else {
            StringBuffer sbf = new StringBuffer();
            for (String id : parentGroupIds) {
                if (sbf.length() > 0) {
                    sbf.append(",");
                }
                sbf.append("'").append(id).append("'");
            }

            return getDao().find("select * from "+ getTable() +" where id in (" + sbf.toString() + ") order by field(id," + sbf.toString() +")");
        }
    }
}

